/**
 * 
 */
package com.toncen.samepms.util;

import java.util.ArrayList;
import java.util.List;

import com.toncen.samepms.basic.domain.User;
import com.toncen.samepms.system.domain.Role;

/**
 * 描述：角色工具类
 * 
 * @author tch
 * 
 */
public final class RoleUtils {
	/**
	 * 是否是指定的角色
	 * 
	 * @param user
	 * @param role
	 * @return
	 * @throws Exception
	 */
	public static boolean isRole(User user, Role role) throws Exception {
		return isRole(user, role.getId());
	}

	/**
	 * 是否是指定的角色
	 * 
	 * @param role
	 * @return
	 * @throws Exception
	 */
	public static boolean isRole(User user, long role) throws Exception {
		boolean result = false;
		for (Role r : user.getRoles()) {
			if (r.getId() == role) {
				return true;
			}
		}
		return result;
	}

	/**
	 * 是否包含指定的角色
	 * 
	 * @param user
	 * @param roles
	 * @return
	 * @throws Exception
	 */
	public static boolean isRole(User user, List<Role> roles) throws Exception {
		boolean result = false;
		for (Role role : roles) {
			result = result || isRole(user, role);
		}
		return result;
	}

	/**
	 * 是否包含指定的角色
	 * 
	 * @param user
	 * @param roles
	 * @return
	 * @throws Exception
	 */
	public static boolean isRole(User user, long[] roles) throws Exception {
		boolean result = false;
		for (long role : roles) {
			result = result || isRole(user, role);
		}
		return result;
	}

	/**
	 * 获取指定用户集合中指定包含指定角色的用户
	 * 
	 * @param userList
	 * @param roles
	 * @return
	 * @throws Exception
	 */
	public static List<User> getRoleUserList(List<User> userList, long[] roles) throws Exception {
		List<User> roleUserList = new ArrayList<User>(5);
		for (User user : userList) {
			for (long role : roles) {
				if (isRole(user, role) && !roleUserList.contains(user)) {// 同一用户多个角色只加一次
					roleUserList.add(user);
					break;
				}
			}
		}
		return roleUserList;
	}

	public static List<User> getRoleUserList(List<User> userList, long role) throws Exception {
		List<User> roleUserList = new ArrayList<User>(5);
		for (User user : userList) {
			if (isRole(user, role)) {
				roleUserList.add(user);
			}
		}
		return roleUserList;

	}
}
